package com.ryskoo.permission.manager.repository;

import com.ryskoo.framework.core.repository.BasicJPAImpl;
import com.ryskoo.permission.dept.domain.DeptPO;
import com.ryskoo.permission.manager.domain.ManagerPO;
import org.hibernate.Query;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;

@Repository
public class ManagerJPAImpl extends BasicJPAImpl<ManagerPO> implements IManagerRepository {

    @Override
    protected String getSelectFields(Class clazz) throws NoSuchFieldException {
        return "o.uuid, o.login_name as loginName, o.password, o.name, o.mobile, o.position, o.identity, o.state, o.email, o.qq, o.dept_id as deptId, d.name as deptName";
    }

    @Override
    protected String getJoinTable() throws NoSuchFieldException {
        // " left join PMS_DEPT d on o.dept_id = d.uuid "
        return " LEFT JOIN " + getTableName(DeptPO.class) + " d ON o." +
                getFieldName(ManagerPO.class, "deptId") + " = d." + getFieldName(ManagerPO.class, "uuid");
    }

	@Override
	protected Query getSqlQuery(String sql, Class modelClass) {
		return getH4Session().createSQLQuery(sql).setResultTransformer(Transformers.aliasToBean(modelClass));
	}

	/**
	 * 根据用户名查询管理员信息
	 * 
	 * @param userName
	 * @return
	 */
	@Override
	public ManagerPO getManagerByLoginName(String userName) {
		String hql = "select o from ManagerPO o where 1=1 and o.loginName =:loginName";
		Query q = this.getH4Session().createQuery(hql);
		q.setString("loginName", userName);
		Object object = q.uniqueResult();
		if (object != null) {
			return (ManagerPO) object;
		}
		return null;
	}

	/**
	 * 根据用户名查询管理员uuid
	 * 
	 * @param userName
	 * @return
	 */
	@Override
	public String getManagerUuidByLoginName(String userName) {
        String hql = "select o.uuid from ManagerPO o where 1=1 and o.loginName =:loginName";
		Query q = this.getH4Session().createQuery(hql);
		q.setString("loginName", userName);
		Object object = q.uniqueResult();
		if (object != null) {
			return (String) object;
		}
		return null;
	}
}
